package RedisSrv

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
)

var ctx = context.Background()
var redisClient *redis.Client

func Redis() *redis.Client {
	if redisClient == nil {
		panic("redis client is null")
	}

	return redisClient
}

func RedisInit(config interface{}) *redis.Client {
	redisConfig := config.(map[string]interface{})
	host := redisConfig["host"]
	port := redisConfig["port"]
	password := redisConfig["password"].(string)
	dbIdx := redisConfig["db"].(float64)
	redisAddr := fmt.Sprintf("%s:%s", host, port)

	redisClient = redis.NewClient(&redis.Options{
		Addr: redisAddr,
		Password: password,
		DB: int(dbIdx),
	})

	_, err := redisClient.Ping(ctx).Result()
	if err != nil {
		panic(err.Error())
	}

	return redisClient
}
